package com.netjava.action;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;
import org.springframework.beans.BeanUtils;

import com.netjava.form.AddProductForm;
import com.netjava.pojo.AucRecord;
import com.netjava.pojo.Auctioning;
import com.netjava.pojo.EndAuction;
import com.netjava.pojo.Preauction;
import com.netjava.pojo.Product;
import com.netjava.service.IAucRecordService;
import com.netjava.service.IAuctioningService;
import com.netjava.service.IEndAuctionService;
import com.netjava.service.IPreauctionService;
import com.netjava.service.IProductService;
import com.netjava.utils.FormatTime;

public class ProductAction extends BaseAction {
	/** 
	 * Method add
	 * 后台添加商品。
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * @throws IOException 
	 */
	@SuppressWarnings("finally")
	public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		AddProductForm productForm=(AddProductForm)form;
		
		//得到文件
		FormFile file1=productForm.getImgFile1();
		FormFile file2=productForm.getImgFile2();
		FormFile file3=productForm.getImgFile3();
		file2=(null==file2.getFileName())?file1:file2;
		file3=(null==file3.getFileName())?file1:file3;
		FormFile[] formFile=new FormFile[]{file1,file2,file3};
		String filePath="",path="";
		try{
		for(int i=0;i<3;i++){
			if(null!=formFile[i].getFileName()){
				//读入文件，得到文件的路径。
				filePath=request.getSession().getServletContext().getRealPath("/")+"/jsp/proimages";
//				path=filePath+"\\"+formFile[i].getFileName();
				System.out.println("path::"+path);
				//创建这个上传的文件的输出流
				File filePathFile=new File(filePath);
				if(!filePathFile.exists()){
					filePathFile.mkdirs();
				}
				
					FileOutputStream fout=new FileOutputStream(filePathFile+"/"+formFile[i].getFileName());
					fout.write(formFile[i].getFileData());
					fout.flush();
					fout.close();
				
				
			}
		}
		}catch(Exception e){
			//e.printStackTrace();
			System.err.println("Caught exception :"+e.getMessage());
		}finally{
		Product product=new Product(); 
		//添加商品
		IProductService service=(IProductService)getBean("productService");
		//将ActionForm的所有字段值转换成POJO对应的字段值
//		BeanCopier copy=BeanCopier.create(AddProductForm.class,Product.class,false);
//		copy.copy(productForm, product, null);
		BeanUtils.copyProperties(productForm,product);
		product.setImage1(file1.getFileName());
		product.setImage2(file2.getFileName());
		product.setImage3(file3.getFileName());
		product.setCurrentPrice(0.00f);
		//当添加一个商品时，让这个商品同时成为即将竞拍的商品
		Preauction preauction=new Preauction();
		preauction.setProduct(product);
		
		preauction.setStartTime(FormatTime.timeFormat());
		product.setPreauction(preauction);
		service.addProduct(product);
		return new ActionForward("/product.do?operation=showAllByState&state=0&page=1&back=1");
		}
	}
	
	/**
	 * Method getByProName
	 * 后台查找商品
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public ActionForward getByProName(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		
		ActionForward forward=mapping.getInputForward();
		IAucRecordService service=(IAucRecordService)getBean("aucRecordService");
		IProductService service1=(IProductService)getBean("productService");
		int state=-1;
		String productName="";
/**
 * remark为备注信息，未修改和删除操作后将返回的页面提供标准。
 * 当remark为1时，返回显示即将竞拍商品页面；
 * remark为2时，返回现实正在竞拍商品；
 * 当remark为3时，返回现实竞拍结束商品；
 */	  	
	  	int remark=0;
		
//得到form
//	  	AddProductForm productForm=(AddProductForm)form;
//	  	productName=productForm.getProductName();
	  	AddProductForm productForm=(AddProductForm)form;
	  	if(productForm!=null){
	  	productName=productForm.getProductName();
	  	}else{
	  		productName=request.getParameter("productName");
	  	}
	  	List<AucRecord> recordList;
	  	Map<Integer,String> aucUser=new HashMap<Integer,String>();
	  	Map<Integer,String> remainTime=new HashMap<Integer,String>();
		//通过商品名查找该商品
		List<Product> productList=service1.getProByName(productName);
		if(productList.size()>0){
		for(Product pro:productList){
			state=pro.getState();
			 if(state==0){
		  			  remainTime.put(pro.getProductId(),"--:--:--");
		  			  aucUser.put(pro.getProductId(),"暂无");
		  		  remark=1;
		  	  }
			 else if(state==1){
		  			  recordList=service.getByProId(pro);
		  			  if(recordList.size()>0){
		  				aucUser.put(pro.getProductId(),recordList.get(0).getUser().getUserName());
		  			  }
		  			  else{
		  				aucUser.put(pro.getProductId(),"暂无");
		  			  }
		  			  remainTime.put(pro.getProductId(),pro.getAuctioning().getRemainTime());
		  		  remark=2;
		  	  }
		  	  else{ 
		  			  recordList=service.getByProId(pro);
		  			  if(recordList.size()>0){
		  				aucUser.put(pro.getProductId(),recordList.get(0).getUser().getUserName());
		  			  }
		  			  else{
		  				aucUser.put(pro.getProductId(),"暂无");
		  			  }
		  			  remainTime.put(pro.getProductId(),"--:--:--");

		  		  remark=3;
		  	  }
		}
		
	  	request.setAttribute("remark",remark);
	  	request.setAttribute("aucUser",aucUser);//最后竞价者
	  	request.setAttribute("remainTime",remainTime);//距离拍卖结束还有的时间
	  	request.setAttribute("productList",productList);
		}else{
			request.setAttribute("NotFund", "你查找的商品不存在，请输入正确的商品名！");
		}
	  	forward=mapping.findForward("show");
		return forward;

	}
	
/**
 * Method delete
 * 后台删除商品
 * @param mapping
 * @param form
 * @param request
 * @param response
 * @return ActionForward
 * @throws FileNotFoundException
 * @throws IOException
 */
	public ActionForward delete(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
		//ActionForward forward=mapping.getInputForward();
		int productId=Integer.parseInt(request.getParameter("productId").toString());
		String productName=null;
/**
 * remark为备注信息，当remark为1时，返回显示即将竞拍商品页面；
 * remark为2时，返回现实正在竞拍商品；
 * 当remark为3时，返回现实竞拍结束商品；
 * 为4时，返回显示以商品名查找商品的页面。
 */
		int remark=Integer.parseInt(request.getParameter("remark").toString());
		//通过商品名查找该商品
		IProductService service1=(IProductService)getBean("productService");
		IPreauctionService service2=(IPreauctionService)getBean("preauctionService");
		IAuctioningService service3=(IAuctioningService)getBean("auctioningService");
		IEndAuctionService service4=(IEndAuctionService)getBean("endAuctionService");
		Product product=service1.getProById(productId);
		service1.delete(product);
		String nextAction = "";

		if(remark==1){
			List<Preauction> preauctionList=service2.getAllPreauc();
			request.getSession().setAttribute("preauctionList",preauctionList);
			nextAction = "/product.do?operation=getByCatalog&state=0";
			return new ActionForward(nextAction, true);  
		}else if(remark==2){
			List<Auctioning> auctioningList=service3.getAllAuc();
			request.getSession().setAttribute("auctioningList",auctioningList);
			nextAction = "/product.do?operation=getByCatalog&state=1";
			return new ActionForward(nextAction, true);  
		}else if(remark==3){
			List<EndAuction> endAuctionList=service4.getAllEndauc();
			request.getSession().setAttribute("endAuctionList",endAuctionList);
			nextAction = "/product.do?operation=getByCatalog&state=2";
			return new ActionForward(nextAction, true);  
		}else{
			productName=product.getProductName();
//			List<Product> proList=service1.getProByName(productName);
//			request.getSession().setAttribute("productList",proList);
			nextAction = "/product.do?operation=getByProName&productName="+productName;
			return new ActionForward(nextAction, true);  
		}
		
	}
	/**
	 * Method getByCatalog
	 * 根据商品分类查找所有商品。
	 * 需要页面传递的参数：state--标识商品状态。
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	@SuppressWarnings({ "unchecked" })
	public ActionForward getByCatalog(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)  {
		ActionForward forward=mapping.getInputForward();
		IAucRecordService service=(IAucRecordService)getBean("aucRecordService");
	  	List<Preauction> preauctionList=(List<Preauction>)request.getSession().getAttribute("preauctionList");
	  	List<Auctioning> auctioningList=(List<Auctioning>)request.getSession().getAttribute("auctioningList");
	  	List<EndAuction> endAuctionList=(List<EndAuction>)request.getSession().getAttribute("endAuctionList");
	  	String states=(String)request.getParameter("state");
	  	List productList=new ArrayList();
	  	String imgSrc="";
/**
 * remark为备注信息，未修改和删除操作后将返回的页面提供标准。
 * 当remark为1时，返回显示即将竞拍商品页面；
 * remark为2时，返回现实正在竞拍商品；
 * 当remark为3时，返回现实竞拍结束商品；
 */	  	
	  	int remark=0;
//	  	String remainTime="";
//	  	String aucUser="";
	  	List<AucRecord> recordList;
	  	Map<Integer,String> aucUser=new HashMap<Integer,String>();
	  	Map<Integer,String> remainTime=new HashMap<Integer,String>();
	  	if(null!=states){
	  	  Integer state=Integer.parseInt(request.getParameter("state").toString());
	  	  if(state==0){
	  		  for(Preauction preauc:preauctionList){
	  			  productList.add(preauc);
	  			  remainTime.put(preauc.getProduct().getProductId(),"--:--:--");
	  			  aucUser.put(preauc.getProduct().getProductId(),"暂无");
 	  		  }
	  		  remark=1;
	  		  imgSrc="jjsj.jpg";
	  	  }
	  	  else if(state==1){
	  		  for(Auctioning auction:auctioningList){
	  			  recordList=service.getByProId(auction.getProduct());
	  			  if(recordList.size()>0){
	  				aucUser.put(auction.getProduct().getProductId(),recordList.get(0).getUser().getUserName());
	  			  }
	  			  else{
	  				aucUser.put(auction.getProduct().getProductId(),"暂无");
	  			  }
	  			  productList.add(auction);
	  			  remainTime.put(auction.getProduct().getProductId(),auction.getRemainTime());
	  			  
	  		  }
	  		  remark=2;
	  		  imgSrc="bg_2.jpg";
	  	  }
	  	  else{ 
	  		  for(EndAuction endAuc:endAuctionList){
	  			  recordList=service.getByProId(endAuc.getProduct());
	  			  if(recordList.size()>0){
	  				aucUser.put(endAuc.getProduct().getProductId(),recordList.get(0).getUser().getUserName());
	  			  }
	  			  else{
	  				aucUser.put(endAuc.getProduct().getProductId(),"暂无");
	  			  }
	  			  productList.add(endAuc);
	  			  remainTime.put(endAuc.getProduct().getProductId(),"--:--:--");
	  			  
	  		  }
	  		  remark=3;
	  		  imgSrc="yjjs.jpg";
	  	  }
	  	}
	  	request.setAttribute("remark",remark);//最后竞价者
	  	request.setAttribute("aucUser",aucUser);//最后竞价者
	  	request.setAttribute("remainTime",remainTime);//距离拍卖结束还有的时间
	  	request.setAttribute("imgSrc",imgSrc);
	  	request.setAttribute("productList",productList);
	  	forward=mapping.findForward("search");
		return forward;
	}
	
	/**
	 * method change
	 * 通过商品id得到商品信息，传个修改页面
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public ActionForward change(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
		int productId=Integer.parseInt(request.getParameter("productId").toString());
		int remark=Integer.parseInt(request.getParameter("remark").toString());
		Product product=new Product(); 
		ActionForward forward=mapping.getInputForward();
		IProductService service=(IProductService)getBean("productService");
		product=service.getProById(productId);
		request.setAttribute("product",product);
		request.setAttribute("remark",remark);
		forward=mapping.findForward("change");
		return forward;
	}
	/**
	 * method update 
	 * 修改商品信息
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
		IProductService service=(IProductService)getBean("productService");
		IPreauctionService service2=(IPreauctionService)getBean("preauctionService");
		IAuctioningService service3=(IAuctioningService)getBean("auctioningService");
		IEndAuctionService service4=(IEndAuctionService)getBean("endAuctionService");
		int remark=Integer.parseInt(request.getParameter("remark").toString());
		int productId=Integer.parseInt(request.getParameter("productId").toString());

		Product product=new Product(); 
		//ActionForward forward=mapping.getInputForward();
		AddProductForm productForm=(AddProductForm)form;
		
		product=service.getProById(productId);
		String image1=product.getImage1();
		String image2=product.getImage2();
		String image3=product.getImage3();
		int state=product.getState();
		Float currentPrice=product.getCurrentPrice();
		//得到文件
		FormFile file1=productForm.getImgFile1();
		FormFile file2=productForm.getImgFile2();
		FormFile file3=productForm.getImgFile3();
		FormFile[] formFile=new FormFile[]{file1,file2,file3};
		//修改商品	
		//将ActionForm的所有字段值转换成POJO对应的字段值
//		BeanCopier copy=BeanCopier.create(AddProductForm.class,Product.class,false);
//		copy.copy(productForm, product, null);
		BeanUtils.copyProperties(productForm,product);
		product.setImage1(file1.getFileName());
		product.setImage2(file2.getFileName());
		product.setImage3(file3.getFileName());
		product.setState(state);
		product.setCurrentPrice(currentPrice);
		String filePath="",path="";
		for(int i=1;i<4;i++){
			if(formFile[i-1].getFileName().length()!=0){
				//读入文件，得到文件的路径。
				filePath=request.getSession().getServletContext().getRealPath("/")+"/jsp/proimages";
				path=filePath+"/"+formFile[i-1].getFileName();
System.out.println("path::"+path);
				//创建这个上传的文件的输出流
				File dir=new File(path);
//				if(!dir.exists()){
//					dir.mkdirs();
//				}
				FileOutputStream fout=new FileOutputStream(dir);
				fout.write(formFile[i].getFileData());
				fout.flush();
				fout.close();

			}
			else{
				if(i==1){
					product.setImage1(image1);
				}
				else if(i==2){
					product.setImage2(image2);
					
				}else{
					product.setImage3(image3);
				}
			}
		}
		service.attachDirty(product);
		String nextAction = "";
		if(remark==1){
			List<Preauction> preauctionList=service2.getAllPreauc();
			request.getSession().setAttribute("preauctionList",preauctionList);
			nextAction = "/product.do?operation=getByCatalog&state=0";
			return new ActionForward(nextAction, true);  
		}else if(remark==2){
			List<Auctioning> auctioningList=service3.getAllAuc();
			request.getSession().setAttribute("auctioningList",auctioningList);
			nextAction = "/product.do?operation=getByCatalog&state=1";
			return new ActionForward(nextAction, true);  
		}else if(remark==3){
			List<EndAuction> endAuctionList=service4.getAllEndauc();
			request.getSession().setAttribute("endAuctionList",endAuctionList);
			nextAction = "/product.do?operation=getByCatalog&state=2";
			return new ActionForward(nextAction, true);  
		}else{
			String productName=product.getProductName();
//			List<Product> proList=service1.getProByName(productName);
//			request.getSession().setAttribute("productList",proList);
			nextAction = "/product.do?operation=getByProName&productName="+productName;
			return new ActionForward(nextAction, true);  
		}
	}
	
	/**
	 * Method :showAll
	 * 需要页面传递的参数：state-商品状态，page-显示第几页，back-是否为后台操作，0:前台，1：后台
	 * 根据状态显示所有商品。
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public ActionForward showAllByState(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response){
		Integer state=Integer.parseInt(request.getParameter("state"));
		Integer page=Integer.parseInt(request.getParameter("page"));
		Integer back=Integer.parseInt(request.getParameter("back"));
		Integer num=4;
		IProductService service=(IProductService)getBean("productService");
		List<Product> pageCutProList=service.pageCutGet(state,page,num);
		//将按分页显示的商品放置到session中。
		request.setAttribute("pageCutProList", pageCutProList);
		//设置当前页
		request.setAttribute("currentPage",page);
		//设置末页
		Integer lastPage=0;
		Integer laseSize=0;
		switch(state)
		{
		case 0:laseSize=(((List<Preauction>)request.getSession().getAttribute("preauctionList"))
				.size());break;
		case 1:laseSize=(((List<Auctioning>)request.getSession().getAttribute("auctioningList"))
				.size());break;
		case 2:laseSize=(((List<EndAuction>)request.getSession().getAttribute("endAuctionList"))
				.size());break;
		default:System.out.println("Not this state products!");break;
		}
		if(laseSize%num==0){
			lastPage=laseSize/num;
			System.out.println("if   laseSize is :"+laseSize);
			System.out.println("if   lastPage is :"+lastPage);
		}else{
			lastPage=laseSize/num+1;
			System.out.println("else  lastPage is :"+lastPage);
			System.out.println("else  laseSize is :"+laseSize);
		}
		request.setAttribute("lastPage",lastPage);
		//设置商品状态
		request.setAttribute("state",state);
		//设置最后竞拍者
		Map<Integer,String> lastBidder=new HashMap<Integer,String>();
		IAucRecordService aucRecordService=(IAucRecordService)getBean("aucRecordService");
		for(Product product:pageCutProList){
			List<AucRecord> aucRecordList=aucRecordService.getByProId(product);
			if(null!=aucRecordList&&aucRecordList.size()>0){
				lastBidder.put(product.getProductId(),aucRecordList.get(0).getUser().getUserName());
			}
		}
		request.setAttribute("lastBidder",lastBidder);
		ActionForward forward=mapping.getInputForward();
		if(back==1){
			forward=mapping.findForward("backByState");
		}else{
			forward=mapping.findForward("allByState");
		}
		request.setAttribute("remark",state+1);
		return forward;
	}
	/**
	 * 
	 * 显示商品所有信息（包括竞拍记录）
	 *
	 */
	public ActionForward showProMsg(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws FileNotFoundException, IOException {
		
		
		
		int productId=Integer.parseInt(request.getParameter("productId"));
			
			//通过产品id找到相应的产品
		IProductService productService=(IProductService)getBean("productService");
		Product product = productService.getProById(productId);
			
		
			//更新当前商品拍卖中的状态属性
			IAuctioningService auctioningService=(IAuctioningService)getBean("auctioningService");
			Auctioning auctioningProduct = auctioningService.getAuctioningById(productId);

			
			//显示商品的拍卖记录
			IAucRecordService aucRecordService=(IAucRecordService)getBean("aucRecordService");
			
			List<AucRecord> aucRecords = aucRecordService.getByProId(product);
			
			//只取10条记录在页面显示
			List<AucRecord> records=new ArrayList<AucRecord>();
			if(aucRecords.size()<10){
			for(int i=0;i<aucRecords.size();i++){
				records.add(aucRecords.get(i));
			}
			}
			else if(aucRecords.size()>=10){
				for(int i=0;i<10;i++){
					records.add(aucRecords.get(i));
				}
			}
				
		request.setAttribute("product", product);
		
		request.setAttribute("auctioningProduct", auctioningProduct);
		request.setAttribute("aucRecords", records);


		ActionForward forward=mapping.getInputForward();
		forward=mapping.findForward("showMsg");
		return forward;
	
	}

}
